import { computed, Ref } from 'vue';

export interface UnifiedAttrEntry { key: string; value: string; raw: any; from: 'local' | 'encoding'; }

interface Options {
  productRef: Ref<{ attributes?: Record<string, any>; code?: string; name?: string } | undefined>;
  encodingDetailRef?: Ref<Record<string, any> | null>;
  max?: number; // 限制展示数量
  includeBaseFields?: boolean; // 是否包含品名/编码基础项
}

// 统一处理：合并 + 单位拼接 + 排序（中文优先使用 localeCompare）+ 来源标记
export function useUnifiedAttributes(opts: Options){
  const max = opts.max ?? 0; // 0 表示不限制
  const includeBase = opts.includeBaseFields ?? false;
  const unified = computed<UnifiedAttrEntry[]>(()=> {
    const prod = opts.productRef.value;
    const base: Record<string, any> = { ...(prod?.attributes || {}) };
    const fromMap: Record<string, 'local' | 'encoding'> = {};
    // 标记本地来源
    Object.keys(base).forEach(k=> { fromMap[k] = 'local'; });
    // 编码平台动态属性
    const encObj = opts.encodingDetailRef?.value || null;
    if(encObj){
      const dyn = (encObj as any).attributes || (encObj as any).dynamicAttributes || encObj; // 兼容字段
      if(dyn && typeof dyn === 'object'){
        for(const [k,v] of Object.entries(dyn)){
          if(['id','code','materialCode','name','category','status','images','mainImageUrl'].includes(k)) continue;
          base[k] = v; // 覆盖或新增
          fromMap[k] = 'encoding';
        }
      }
    }
    // 生成条目
    let entries: UnifiedAttrEntry[] = Object.entries(base).map(([k,v])=> {
      let display = '';
      if(v && typeof v === 'object' && 'value' in (v as any)){
        const obj = v as any; display = obj.unit ? `${obj.value}${obj.unit}` : String(obj.value);
      } else {
        display = String(v);
      }
      return { key: k, value: display, raw: v, from: fromMap[k] || 'local' };
    });
    // 追加基础项（品名/编码）放前面
    if(includeBase && prod){
      const baseItems: UnifiedAttrEntry[] = [];
      if(prod.name) baseItems.push({ key: '品名', value: prod.name, raw: prod.name, from: 'local' });
      if(prod.code) baseItems.push({ key: '编码', value: prod.code, raw: prod.code, from: 'local' });
      entries = [...baseItems, ...entries];
    }
    // 排序：对 key 做 localeCompare（中文 + 英文混排），保持基础项前置
    const offset = includeBase ? (entries[0]?.key === '品名' ? 2 : 0) : 0;
    const head = entries.slice(0, offset);
    const tail = entries.slice(offset).sort((a,b)=> a.key.localeCompare(b.key,'zh-Hans-CN'));
    const merged = [...head, ...tail];
    return max > 0 ? merged.slice(0,max) : merged;
  });
  return { unified };
}
